package core.component;

import core.api.RetryPolicy;

import java.util.Collections;
import java.util.Set;

public class DefaultRetryPolicy implements RetryPolicy {
    private static final int DEFAULT_MAX_ATTEMPTS = 3;
    private static final long DEFAULT_DELAY_MS = 1000;
    
    private final int maxAttempts;

    // 如果不为空 出现以下异常允许重试
    private final Set<Class<? extends Exception>> retryableExceptions;
    
    public DefaultRetryPolicy() {
        this(DEFAULT_MAX_ATTEMPTS, Collections.emptySet());
    }
    
    public DefaultRetryPolicy(int maxAttempts,
                            Set<Class<? extends Exception>> retryableExceptions) {
        this.maxAttempts = maxAttempts;
        this.retryableExceptions = retryableExceptions != null ? 
            retryableExceptions : Collections.emptySet();
    }
    
    @Override
    public boolean shouldRetry(int retryCount, Exception lastException) {
        if (retryCount >= maxAttempts) {
            return false;
        }
        
        if (retryableExceptions.isEmpty()) {
            return true;
        }
        
        return retryableExceptions.stream()
            .anyMatch(clazz -> clazz.isInstance(lastException));
    }

    @Override
    public int getMaxAttempts() {
        return maxAttempts;
    }
}